package com.lecture.junit.tdd.example;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class AccountPasswordsCollection {
    private final int maxElementsCount;
    private final LinkedHashMap<String, String> passwords;

    public class PasswordMap<K, V> extends LinkedHashMap<K,V> {
        public  PasswordMap(int capacity) {
            super(capacity);
        }
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() == maxElementsCount;
        }
    }

    public AccountPasswordsCollection(int capacity) {
        this.maxElementsCount = capacity;
        passwords = new PasswordMap<>(capacity);
    }

    public synchronized void add(String password) throws OldPasswordException {
        if (passwords.containsKey(password)) {
            throw new OldPasswordException("Password was used recentlry. Choose the other one.");
        }
        passwords.put(password, password);
    }
}
